﻿using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using YWM.DependencyInjection;
using YWM.Entities;
using YWM.Entities.Extensions;
using YWM.Session;

namespace YWM.EntityFramework
{
    /// <summary>
    /// 应用数据库上下文
    /// </summary>
    /// <typeparam name="TDbContext">数据库上下文</typeparam>
    public abstract class EFDbContext : DbContext, IScoped
    {
        private readonly ISession _session;
        public EFDbContext(string nameOrConnectionString) : base(nameOrConnectionString)
        {
            _session = YApp.Resolve<ISession>();
        }

        /// <summary>
        /// 数据库上下文配置模型调用方法
        /// </summary>
        /// <param name="modelBuilder"></param>
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            //防止EF框架自动加s
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
            base.OnModelCreating(modelBuilder);
        }

        public override int SaveChanges()
        {
            SavingChangesEvent();
            int result = base.SaveChanges();
            SavedChangesEvent(result);
            return result;
        }

        public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = default(CancellationToken))
        {
            SavingChangesEvent();
            Task<int> result = base.SaveChangesAsync(cancellationToken);
            SavedChangesEventAsync(result);
            return result;
        }

        protected virtual void SavingChangesEvent()
        {
            IEnumerable<DbEntityEntry> entries = ChangeTracker.Entries()
                .Where(e => e.State == EntityState.Added || e.State == EntityState.Modified || e.State == EntityState.Deleted);
            foreach (DbEntityEntry entry in entries)
            {
                FilterNull(entry);
                object entity = entry.Entity;
                switch (entry.State)
                {
                    case EntityState.Added:
                        entity.SetCreationProperties(_session.SubjectId);
                        break;
                    case EntityState.Modified:
                        if (entity.IsSoftDelete())
                        {
                        }
                        else
                        {
                            entity.SetModificationProperties(_session.SubjectId);
                        }
                        break;
                    case EntityState.Deleted:
                        break;
                }
            }
        }

        private void FilterNull(DbEntityEntry entry)
        {
            object entity = entry.Entity;
            foreach (var item in entity.GetType().GetProperties())
            {
                if (entry.State == EntityState.Modified && item.Name.Equals(nameof(Entity.Id)))
                {
                    continue;
                }
                DbPropertyEntry propertyEntry = entry.Property(item.Name);
                if (propertyEntry.IsModified)
                {
                    entry.Property(item.Name).IsModified = item.GetValue(entity) != null;
                }
            }
        }

        protected virtual void SavedChangesEvent(int result)
        {
        }

        protected virtual Task SavedChangesEventAsync(Task<int> result)
        {
            return Task.CompletedTask;
        }
    }
}